package servlet;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import bean.UserBean;
import dao.LoginDao;
import net.sf.json.JSONObject;

/**
 * Servlet implementation class LoginServler
 */
@WebServlet("/LoginServler")
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public LoginServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		InputStream is = request.getInputStream();
		BufferedReader br = new BufferedReader(new InputStreamReader(is));
		StringBuffer data = new StringBuffer();
		String buffer;
		while((buffer = br.readLine())!=null) {
			data.append(buffer);
		}
		
		String name, password;
		JSONObject userJson = JSONObject.fromObject(data.toString());
		name = userJson.getString("name");
		password = userJson.getString("password");
		String result = "";
		UserBean user = new UserBean();
		try {
			if((new LoginDao()).checkLogin(name, password, user)) {
				result = "OK";
			}
			else {
				result = "ERROR";
			}
		} catch (Exception e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		}
		
		JSONObject repJson = JSONObject.fromObject(user);
		repJson.put("result", result);
		OutputStream os = response.getOutputStream();
		BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os));
		bw.write(repJson.toString());
		bw.flush();
		bw.close();
	}

}
